<template>
    <div class="view_tracker_returning">
        <card title="传感器退货">
            <template #actions>
                <el-select class="w-32" v-model="queryBy">
                    <el-option v-for="(val, key) in queryBySomething" :key="key" :value="key" :label="val" />
                </el-select>
                <el-input
                    class="w-48"
                    v-model="queryString"
                    :placeholder="placeholder"
                    prefix-icon="el-icon-search"
                    clearable
                />
                <el-button type="primary" @click="add">添加退货订单</el-button>
            </template>

            <template #default>
                <el-table :data="tableData">
                    <el-table-column type="index" label="#" align="center" />
                    <el-table-column prop="sellerName" label="店铺名" />
                    <el-table-column prop="trackerRefundSn" label="退货单号" />
                    <el-table-column prop="quantity" label="数量" />
                    <el-table-column label="订单类型">
                        <template #default="{ row: { orderType } }">
                            <el-tag :type="returnedTrackerOrderTypes[orderType].tagType">
                                {{ returnedTrackerOrderTypes[orderType].text }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单状态">
                        <template #default="{ row: { orderStatus } }">
                            <el-tag effect="dark" :type="returnedTrackerOrderStatus[orderStatus].tagType">
                                {{ returnedTrackerOrderStatus[orderStatus].text }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" />
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <el-button type="text" @click="view(row.trackerOrderId)">查看详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <template #bottom-right>
                <el-pagination
                    @current-change="query"
                    :currentPage.sync="currentPage"
                    :total="total"
                    :pageSize="pageSize"
                />
            </template>
        </card>

        <!-- 传感器未使用数量对话框 -->
        <el-dialog :visible.sync="visible" title="待退货店铺列表" custom-class="unreturned_shops">
            <el-input
                class="unreturned_shops-search_box"
                v-model="unreturnedShopQueryString"
                prefix-icon="el-icon-search"
                placeholder="按店铺名查找"
                clearable
            />
            <el-table :data="unreturnedShops">
                <el-table-column type="index" label="#" align="center" />
                <el-table-column prop="sellerName" label="店铺名" />
                <el-table-column prop="num" label="数量" />
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button type="text" @click="openReturningDialog(row)">退货</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <!-- 退货对话框 -->
        <el-dialog
            :visible.sync="visible2"
            title="传感器退货"
            custom-class="returning_dialog"
            @closed="closeReturningDialog"
        >
            <template #default>
                <el-alert>
                    <p>当前店铺待退货数量：{{ formData.quantity }}</p>
                </el-alert>
                <div class="input_box">
                    <div class="input_box-label">收货人</div>
                    <input v-model="formData.receiverName" type="text" class="input_box-control" />
                </div>
                <div class="input_box">
                    <div class="input_box-label">收货人联系电话</div>
                    <input v-model="formData.receiverPhone" type="text" class="input_box-control" />
                </div>
                <div class="input_box">
                    <div class="input_box-label">收货地址</div>
                    <input v-model="formData.receiverAddress" type="text" class="input_box-control" />
                </div>
                <div class="input_box">
                    <div class="input_box-label">传感器</div>
                    <textarea v-model="formData.vid" type="text" class="input_box-control" rows="5" />
                </div>
            </template>
            <template #footer>
                <el-button type="primary" @click="$return">退货</el-button>
            </template>
        </el-dialog>

        <!-- 订单详情对话框 -->
        <el-dialog :visible.sync="visible3" custom-class="details_dialog">
            <template #default>
                <div class="desc_list">
                    <div class="desc_list-top">
                        <h1 class="desc_list-title">{{ details.trackerOrderSn }}</h1>
                        <p class="desc_list-subtitle">店铺名：{{ details.sellerName }}</p>
                    </div>
                    <dl class="desc_list-content">
                        <div class="desc_list-item">
                            <dt>数量</dt>
                            <dd>{{ details.quantity }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>订单类型</dt>
                            <dd>{{ returnedTrackerOrderTypes[details.orderType].text }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>创建时间</dt>
                            <dd>{{ details.createTime }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>退货传感器列表</dt>
                            <dd>{{ details.vidList }}</dd>
                        </div>
                    </dl>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getQueryOptions } from '../../mixins';
import debounce from 'lodash.debounce';

const defaultFormData = {
    vid: '',
    sellerId: '',
    quantity: '',
    receiverName: '',
    receiverPhone: '',
    receiverAddress: '',
};

const copiedDefaultFormData = Object.assign({}, defaultFormData);

export default {
    data() {
        return {
            tableData: [],

            formData: defaultFormData,
            queryBy: 'sellerName',

            visible: false,
            visible2: false,
            visible3: false,

            // 未退货的店铺
            unreturnedShops: [],
            unreturnedShopQueryString: '',

            // 订单详情
            details: {},
        };
    },

    mixins: [
        getQueryOptions({
            apiurl: '/yxl/platform/findRefund',
            paginable: true,
            params: {
                queryString: 'queryBy',
            },
        }),

        // getAdditionOptions({
        //     apiurl: '/yxl/platform/saveReturnOrder',
        //     formDataProperty: 'formData',
        // }),
    ],

    computed: {
        // 按某物查询
        queryBySomething() {
            return {
                sellerName: '店铺名',
                trackerRefundSn: '退货单号',
            };
        },
        // 搜索框占位符
        placeholder() {
            return `按${this.queryBySomething[this.queryBy]}查询`;
        },

        // 退货的传感器订单状态（与普通订单状态保持一致）
        returnedTrackerOrderStatus() {
            return {
                1: { text: '待发货', tagType: 'warning' },
                2: { text: '已发货', tagType: 'success' },
                3: { text: '已完成', tagType: 'success' },
                4: { text: '待付款' },
                5: { text: '已关闭', tagType: 'info' },
                6: { text: '已取消', tagType: 'info' },
                7: { text: '已退款', tagType: 'danger' },
            };
        },

        // 退货的传感器订单类型
        returnedTrackerOrderTypes() {
            return {
                1: { text: '免租' },
                2: { text: '押金', tagType: 'success' },
                3: { text: '补货', tagType: 'warning' },
                4: { text: '退货', tagType: 'danger' },
            };
        },
    },

    watch: {
        unreturnedShopQueryString: debounce(function () {
            this.getUnreturnedShops();
        }, 600),
    },

    methods: {
        // 获取未退货的店铺列表
        getUnreturnedShops() {
            return this.$get('/yxl/platform/findReturned', { sellerName: this.unreturnedShopQueryString }).then(res => {
                this.unreturnedShops = Object.freeze(res);
            });
        },

        // 打开退货对话框
        openReturningDialog(row) {
            this.formData.sellerId = row.sellerId;
            this.formData.quantity = row.num;

            this.visible2 = true;
        },

        // 关闭对话框
        closeReturningDialog() {
            Object.assign(this.formData, copiedDefaultFormData);
        },

        // 添加退货订单
        add() {
            if (this.unreturnedShops.length) {
                this.visible = true;
                return;
            }

            this.getUnreturnedShops().then(res => {
                this.visible = true;
            });
        },

        // 验证传感器id格式
        // 如果格式不正确给出对应提示并返回false，如果格式正确返回格式化后的id列表
        verifyTrackersIdFormat(vid) {
            if (vid.includes('\n') && vid.includes(',')) {
                this.$message.error('回车换行不需要带逗号');
                return;
            }

            if (!/^(8\d{14},?)+\b$/.test((vid = vid.replace(/\n/g, ',')))) {
                this.$message.error('传感器id格式不正确');
                return;
            }

            return true;
        },

        // 退货
        $return() {
            this.formData.vid = this.formData.vid.trim();
            if (this.verifyTrackersIdFormat(this.formData.vid)) {
                this.$put('/yxl/platform/saveReturnOrder', this.formData).then(res => {
                    this.visible2 = false;

                    // 自动刷新数据
                    this.getUnreturnedShops();
                    this.query();
                });
            }
        },

        // 查看订单详情
        view(trackerOrderId) {
            this.$get('/yxl/platform/findRefundDetails', { trackerOrderId }).then(res => {
                this.details = Object.freeze(res);

                this.visible3 = true;
            });
        },
    },
};
</script>